package cz.schovjan.proj.filters;

import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cz.schovjan.proj.controllers.Base;
import cz.schovjan.proj.model.User;
import cz.schovjan.proj.util.StringUtil;

/**
 * Autorizacni filtr.
 * Hlida uzivatele pri vstupu na konkretni stranky a 
 * overuje jejich autorizaci.
 * @author schovjan
 *
 */
public class AuthentFilter extends Base implements Filter {

	private ArrayList<String> urlsVisitor;
	private ArrayList<String> urlsUser;
	
	
	public void init(FilterConfig config) throws ServletException {
		urlsVisitor = new ArrayList<String>();
		urlsUser = new ArrayList<String>();
		
		// naplneni stranek kam smi navstevni
		String urls = config.getInitParameter("avoid-urls-visitor");
	    StringTokenizer token = new StringTokenizer(urls, ",");
	 
	    while (token.hasMoreTokens()) {
	    	String s = token.nextToken();
	    	s = s.replaceAll("\\s", "");
	    	urlsVisitor.add(s);
	    }
	    
	    // naplneni stranek kam smi prihlaseny uzivatel
	    urls = config.getInitParameter("avoid-urls-user");
	    token = new StringTokenizer(urls, ",");
	 
	    while (token.hasMoreTokens()) {
	    	String s = token.nextToken();
	    	s = s.replaceAll("\\s", "");
	    	urlsUser.add(s);
	    }
	}
	

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		HttpSession session = ((HttpServletRequest) request).getSession();
		HttpServletResponse res = (HttpServletResponse) response;
		HttpServletRequest req = (HttpServletRequest) request;
		
		// zjistim uzivatele a adresu kam chce jit
		User user = (User) session.getAttribute("user");
		String cp = req.getContextPath(); //napr. /proj/
		String sp = req.getServletPath(); //napr. /band/summary
		boolean err = true;
		
		if (sp.equals("/") || sp.startsWith("/resources") || sp.startsWith("/error")) {
			chain.doFilter(request, response);
		}
		else if (user == null) {
			// visitor muze vstoupit pouze na urcite stranky, jinak error
			for (String uv : urlsVisitor) {	if (sp.startsWith(uv)) { err = false; }	}
			
			if (err) {
				res.sendRedirect(cp+"/error/"+StringUtil.toSecretString(MSG_ACCESS_DENIED));	
				}
			else {
				chain.doFilter(request, response); 
			}
		} else if (user.isRoleUser()) {
			// user muze vstoupit pouze na stranky visitora a navic sve, jinak error
			for (String uv : urlsVisitor) {	if (sp.startsWith(uv)) { err = false; }	}
			for (String uv : urlsUser)	  { if (sp.startsWith(uv)) { err = false; } }
			
			if (err) {
				res.sendRedirect(cp+"/error/"+StringUtil.toSecretString(MSG_ACCESS_DENIED));
			} else {
				chain.doFilter(request, response); 
			}
		} else if (user.isRoleAdmin()) {
			// admin ma neomezeny pristup na vsechny stranky
			chain.doFilter(request, response);
		}

		getLogger().info("F > " + session.getAttribute("user"));
		
	}
	

	public void destroy() {
	}

}
